﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace RFW.Silverlight.Weather
{
	public class Alerts
	{
		private List<Alert> _alerts = null;
		private string _locationCode = string.Empty;
		private string _uri = "http://api.wunderground.com/auto/wui/geo/AlertsXML/index.xml?query={0}";

		public event System.EventHandler DownloadComplete;
		public event System.EventHandler DownloadFailed;

		public Alerts()
			: this("49120")
		{
		}

		public Alerts(string locationCode)
		{
			_locationCode = locationCode;
		}

		public string LocationCode
		{
			get { return _locationCode; }
			set { _locationCode = value; }
		}

		public List<Alert> Items
		{
			get { return _alerts; }
		}

		public void Get()
		{
			try
			{
				System.Net.WebClient wc = new WebClient();
				wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
				wc.DownloadStringAsync(new Uri(string.Format(_uri, _locationCode)));
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				if (DownloadFailed != null)
					DownloadFailed(this, EventArgs.Empty);
			}
		}

		void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			_alerts = new List<Alert>();

			try
			{
				XDocument doc = XDocument.Parse(e.Result);

				_alerts =
					(
						from alert in doc.Element("alerts").Elements("alert")
						select new Alert
						{
							Type = alert.Element("AlertItem").Element("type").Value,
							Description = alert.Element("AlertItem").Element("description").Value,
							DateTime = alert.Element("AlertItem").Element("date").Value,
							Expires = alert.Element("AlertItem").Element("expires").Value,
							Message = alert.Element("AlertItem").Element("message").Value
						}
					).ToList();

				if (DownloadComplete != null)
					DownloadComplete(this, EventArgs.Empty);
			}
			catch (Exception ex)
			{
				_alerts = null;

				System.Diagnostics.Debug.WriteLine(ex.Message);
				if (DownloadFailed != null)
					DownloadFailed(this, EventArgs.Empty);
			}
		}
	}
}
